package com.hbu.fleastreet.controller.backend;

import com.hbu.fleastreet.common.Constant;
import com.hbu.fleastreet.entity.Product;
import com.hbu.fleastreet.entity.ProductTag;
import com.hbu.fleastreet.entity.ProductType;
import com.hbu.fleastreet.entity.Result;
import com.hbu.fleastreet.entity.ResultCode;
import com.hbu.fleastreet.services.ICategoryService;
import com.hbu.fleastreet.services.IProductService;
import com.hbu.fleastreet.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 后端产品上下架
 */
@Controller
@RequestMapping("/manager/product")
public class ManagerProductController {
	Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private IProductService productService;
	@Autowired
	private ICategoryService categoryService;
	//    @Autowired
	//    private ClassificationService classificationService;

	@GetMapping("/list")
	public String toList() {
		return "/backend/product/list";
	}

	@GetMapping("/add")
	public String toAdd() {
		return "/backend/product/add";
	}

	/**
	 * 分页查询
	 * @param pageindex
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@PostMapping("/list/{pageindex}")
	public Result<List<Product>> listProduct(@PathVariable("pageindex") Integer pageindex,
			@RequestParam(defaultValue = "7", value = "pageSize", required = false) Integer pageSize) {
		List<Product> list = productService.findProductByIndex(pageindex, pageSize).getList();
		return new Result<List<Product>>(ResultCode.SUCCESS, list);
	}

	/**
	 * 用于获取分页时总数
	 * @return
	 */
	@ResponseBody
	@GetMapping("/total")
	public Result<Integer> getTotal() {
		int total = productService.countAll();
		return new Result<>(ResultCode.SUCCESS, total);
	}

	@GetMapping("/img/{filename}")
	public void getImage(@PathVariable(name = "filename", required = true) String filename,
			HttpServletResponse res) throws IOException, UnsupportedEncodingException {
		//图片地址 img/product/100007.jpg
		File file = new File(Constant.PREFIX_URL_SAVE_IMAGE +"/"+filename+".jpg");
		if (file != null && file.exists()) {
			res.setHeader("content-type", "application/octet-stream");
			res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
			res.setContentLengthLong(file.length());
			Files.copy(Paths.get(file.toURI()), res.getOutputStream());
		}
	}

	/**
	 * 此处数据库自增id不利于两个表字段关联，不好获取。同一个事务中。
	 * 考虑合并两个表，或者代码控制id自增
	 * 决定使用代码控制id自增
	 * 另外图片保存，直接使用id关联
	 * **/
	@PostMapping(value = "/add")
	public void add(MultipartFile fileselect,
			String name,
			int number,
			Double price,
			Integer typeId,
			String productContent,
			String tagContent,
			int state,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//获取下一个产品id,作为主键，应用于product表和productContent表等
		int productId = productService.nextVal();
		//构建入库对象
		Product product = new Product();
		product.setProductId(productId);
		product.setName(name);
		product.setNumber(number);
		product.setPrice(price);
		product.setState(state);
		product.setProductTypeId(typeId);
		ProductTag productTag = new ProductTag(productId, productContent, tagContent,state);
		//图片写入文件系统
		FileUtil.saveFile(fileselect, productId);
		boolean flag = false;
		try {
			//入库操作
			productService.insertProductAndProductTag(product, productTag);
			flag = true;
		} catch (Exception e) {
			log.error(Arrays.toString(e.getStackTrace()));
		}
		if (!flag) {
			request.setAttribute("message", "添加失败！");
			request.getRequestDispatcher("/fleastreet/manager/product/add").forward(request, response);
		} else {
			response.sendRedirect("/fleastreet/manager/product/list");
		}
	}

	@PostMapping("/update")
	public void update(int productId,
			String name,
			int number,
			Double price,
			Integer productTypeId,
			String productContent,
			String tagContent,
			int state,
			MultipartFile fileselect,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Product product = productService.getProductById(productId);
		product.setName(name);
		product.setPrice(price);
		product.setNumber(number);
		product.setState(state);
		product.setProductTypeId(productTypeId);
		product.setProductId(productId);
		ProductTag productTag = new ProductTag(productId, productContent, tagContent,state);
		FileUtil.saveFile(fileselect, productId);
		boolean flag = false;
		try {
			productService.updateProductAndProductTag(product, productTag);
			flag = true;
		} catch (Exception e) {
			log.error(Arrays.toString(e.getStackTrace()));
		}
		if (!flag) {
			request.setAttribute("message", "更新失败！");
		}
		response.sendRedirect("/fleastreet/manager/product/list");
	}

	@RequestMapping("/edit/{productId}")
	public String editProduct(@PathVariable("productId") int productId, Map<String, Object> map) {
		Product product = productService.getProductById(productId);
		ProductTag productTag = productService.getProductTagById(productId);
		ProductType type = categoryService.findTypeById(product.getProductTypeId());
		map.put("product", product);
		map.put("productTag", productTag);
		map.put("type", type);
		return "/backend/product/edit";
	}

	@RequestMapping("/del/{productId}")
	@ResponseBody
	public Result<Boolean> delProduct(@PathVariable("productId") int productId) {
		//TODO 后续增加删除图片操作
		productService.delProductByProductId(productId);
		return new Result<Boolean>(ResultCode.SUCCESS, true);
	}

}
